/**
* coder  : dzlua
* email  : 505544956@qq.com
* module : ApiMgr-client
* path   : src/utils
* file   : index.js
* time   : 2017-11-16 16:01:23
*/

function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

function filterNull (o) {
  for (let key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    switch (toType(o[key])) {
      case 'string':
        o[key] = o[key].trim()
        break
      case 'object':
      case 'array':
        o[key] = filterNull(o[key])
        break
    }
  }
  return o
}

/*
  let data = {
    'a': 111,
    'b': 222,
    'g': 999
  }
  let obj = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': null
  }
  let arr = ['a', 'b']
  window.alert(JSON.stringify(this.$utils.filter(data, arr)))
  window.alert(JSON.stringify(this.$utils.filter(data, obj)))
  ====>
  {"a":111,"b":222}
  {"a":111,"b":222,"c":3}
*/
function filter (obj, arrobj) {
  let data = {}
  if (!obj) return data
  if (!arrobj) return obj

  let k = null
  let v = null
  switch (toType(arrobj)) {
    case 'array':
      for (k in arrobj) {
        k = arrobj[k]
        v = obj[k]
        if (v) data[k] = v
      }
      break
    case 'object':
      for (k in arrobj) {
        v = obj[k] || arrobj[k]
        if (v) data[k] = v
      }
      break
  }

  return data
}

export default {
  toType: toType,
  filterNull: filterNull,
  filter: filter
}
